package com.example.controller;

import com.example.annotation.UserAuth;
import com.example.dto.ResetPasswordDTO;
import com.example.dto.SecUserDTO;
import com.example.model.SecUser;
import com.example.service.SecUserService;
import com.example.tools.ApiResult;
import com.example.tools.Constant;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author liheng
 * @since 2020-08-26
 */
@Slf4j
@Api(tags = {"管理员设置相关接口"})
@RestController
@RequestMapping("/sys-user/")
@CrossOrigin
@UserAuth
public class SecUserController {
    private final SecUserService secUserService;

    @Autowired
    public SecUserController(SecUserService secUserService) {
        this.secUserService = secUserService;
    }


    @ApiOperation("新增-编辑-新增或编辑用户")
    @PostMapping("addOrUpdateUser")
    public ApiResult<String> addOrUpdateUser(@Validated @RequestBody SecUserDTO dto) {
        secUserService.addOrUpdateUser(dto);
        return ApiResult.ok();
    }

    @ApiOperation("重置密码")
    @PostMapping("resetPassword")
    public ApiResult<String> resetPassword(@Validated @RequestBody ResetPasswordDTO dto) {
        SecUser secUser = secUserService.getById(dto.getId());
        if (StrUtil.isNotBlank(dto.getPassword())) {
            // 修改密码
            secUser.setPassword(dto.getPassword());
        } else {
            // 重置密码
            secUser.setPassword(Constant.DEF_PASSWORD);
        }
        secUserService.updateById(secUser);
        return ApiResult.ok();
    }


    @ApiOperation(value = "删除-删除用户", notes = "删除用户")
    @DeleteMapping("del/{uid}")
    public ApiResult<String> delUser(@PathVariable Integer uid) {
        if (uid.equals(1)) {
            return ApiResult.ok();
        }
        secUserService.removeById(uid);
        return ApiResult.ok();
    }

}

